<?php

/*
 * This file is part of the symfony package.
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * sfWidgetFormSelectDoubleList represents a multiple select displayed as a double list.
 *
 * This widget needs some JavaScript to work. So, you need to include:
 *
 *   /sfFormExtraPlugin/js/double_list.js
 *
 * You also need to add an "onsubmit" attribute to your form tag:
 *
 *   onsubmit="double_list_submit(this, 'double_list_select'); return true;"
 *
 * @package    symfony
 * @subpackage widget
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id: sfWidgetFormSelectDoubleList.class.php 11840 2008-09-29 09:23:27Z fabien $
 */
class sfWidgetFormPropelSelectDoubleList extends sfWidgetFormSelectDoubleList
{
	public function __construct($options = array(), $attributes = array())
	{
		$options['choices'] = new sfCallable(array($this, 'getChoices'));
		parent::__construct($options, $attributes);
	}

	protected function configure($options = array(), $attributes = array())
	{
		$this->addRequiredOption('model');
		$this->addOption('method', '__toString');
		$this->addRequiredOption('peer_method', 'doSelect');
		$this->addRequiredOption('id_method', 'getPrimaryKey');
		$this->addOption('order_by', null);
		$this->addOption('criteria', null);
		$this->addOption('connection', null);

		parent::configure($options, $attributes);

	}

	public function getChoices()
	{
		$choices = array();

		$class = $this->getOption('model').'Peer';

		$criteria = is_null($this->getOption('criteria')) ? new Criteria() : $this->getOption('criteria');
		if ($order = $this->getOption('order_by'))
		{
			$method = sprintf('add%sOrderByColumn', 0 === strpos(strtoupper($order[1]), 'ASC') ? 'Ascending' : 'Descending');
			$criteria->$method(call_user_func(array($class, 'translateFieldName'), $order[0], BasePeer::TYPE_PHPNAME, BasePeer::TYPE_COLNAME));
		}
		$objects = call_user_func(array($class, $this->getOption('peer_method')), $criteria, $this->getOption('connection'));

		$method = $this->getOption('method');
		foreach ($objects as $object)
		{
			$choices[call_user_func(array($object, $this->getOption('id_method')))] = $object->$method();
		}

		return $choices;
	}

	public function __clone()
	{
		$this->setOption('choices', new sfCallable(array($this, 'getChoices')));
		parent::__clone();
	}
}
